package com.will.txj.aj.security.config.auth;

import com.will.txj.common.result.R;
import com.will.txj.common.result.RC;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: wen-yi;
 * @date: 2021/12/5 22:17;
 * @Description: 登录超时处理
 */
@Component("myInvalidSessionStrategy")
public class MyInvalidSessionStrategy implements InvalidSessionStrategy {
    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 要将浏览器中的cookie的jsessionid删除
        cancelCookie(request, response);
        JSONAuthenticationUtil.WriteJSON(request, response, R.fail(RC.USER_SESSION_INVALID));
    }
    protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("OAUTH2-CLIENT-SESSIONID-12000", null);
        cookie.setMaxAge(0);
        cookie.setPath(getCookiePath(request));
        response.addCookie(cookie);
    }

    private String getCookiePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    }
}
